<route>
    {
        meta: {
            layout: 'index',
            title:'仪器信息管理'
        }
    }  
</route>
<template>
  <view>
    <div class="app-container">
      <a-row>
        <a-input-search v-model:value="searchKey" placeholder="请输入仪器信息" enter-button="搜索"
          style="width: 250px; margin-bottom: 10px" @search="handleQuery()" />
        <a-button style="margin-left: 10px" type="dashed" @click="reset">重置</a-button>
        <a-space>
          <a-select ref="select" v-model:value="instrumentType" placeholder="系列选择"
            style="width: 150px; margin-bottom: 10px; margin-left: 50px;" @focus="focus">
            <a-select-option value="CPLog">CPLog</a-select-option>
            <a-select-option value="5700">5700</a-select-option>
          </a-select>
        </a-space>
        <a-button type="primary" style="margin-left: auto; margin-bottom: 10px; width: 100px" @click="addItem">
          <template #icon><plus-outlined /></template>新增
        </a-button>
      </a-row>

      <a-table :dataSource="dataSource" :columns="columns" bordered :scroll="{ x: 1000, y: 600 }" :pagination="false">
        <template #bodyCell="{ column, text, record }">
          <!-- <template
            v-if="['outerDiameter', 'weight', 'length', 'longitudinalPressure', 'longitudinalTension', 'torsionResistance', 'maxWell', 'minWell', 'record', 'temperatureResistance', 'transportationLength', 'voltageResistance',].includes(column.dataIndex)">
            <div>
              <a-input-number v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex]"
                :min="0" style="margin: -5px 0" />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-if="['loggingContent'].includes(column.dataIndex)">
            <div>
              <a-input v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex]"
                style="margin: -5px 0" />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template> -->
          <template v-if="column.dataIndex === 'image'">
            <div style="margin-right: 8px">
              <!-- <a-image :width="200" :src="`http://wellb.apisev.cn/ufs/download/${record.fileId}`" /> -->
              <a-image class="rotated-image" :width="20" style="height: 100px;"
                :src="`/dev-api/ufs/preview/${record.fileId}`" />
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <div style="margin-right: 8px">
              <!-- <span v-if="editableData[record.id]">
                <a-button type="link" @click="save(record.id)">保存 </a-button>
                <a-popconfirm title="取消编辑 ?" @confirm="cancel(record.id)">
                  <a-button type="link">取消</a-button>
                </a-popconfirm>
              </span> -->
              <span>
                <a-button type="link" @click="editItem(record)">编辑</a-button>
                <AntdZh><a-popconfirm title="确定删除该条记录 ?" @confirm="del(record.id)">
                  <a-button type="link" danger>删除</a-button>
                </a-popconfirm></AntdZh>
              </span>
            </div>
          </template>
        </template>
      </a-table>
      <AntdZh>
        <a-pagination v-model:current="query.pageNum" v-model:pageSize="query.pageSize" :total="total"
          @change="getList" />
      </AntdZh>

      <!-- 新版添加或修改部门对话框 -->
      <AntdConfirmModal :title="title ? '新增仪器' : '编辑仪器'" ref="modalRef" width="700px" :keepSlot="false"
        @confirm="submitForm">
        <a-form :model="form" name="basic" :label-col="{ span: 10 }">
          <a-row>
            <a-col :span="12">
              <a-form-item label="规格型号" name="instrumentId" :rules="[{ required: true, message: '请输入规格型号' }]">
                <a-input v-model:value="form.instrumentId" style="width: 150px" placeholder="请输入规格型号" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="仪器名称" name="instrumentName" :rules="[{ required: true, message: '请输入仪器名称' }]">
                <a-input v-model:value="form.instrumentName" style="width: 150px" placeholder="请输入仪器名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="装备类型" name="instrumentType">
                <a-input v-model:value="form.instrumentType" style="width: 150px" controls-position="right" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="设备类别" name="category">
                <a-input v-model:value="form.category" style="width: 150px" controls-position="right" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="装备系列" name="instrumentSeries">
                <a-input v-model:value="form.instrumentSeries" style="width: 150px" controls-position="right" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="装备子系列" name="instrumentChildSeries">
                <a-input v-model:value="form.instrumentChildSeries" style="width: 150px" controls-position="right" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="主/子设备" name="instrumentLevel">
                <a-input v-model:value="form.instrumentLevel" style="width: 150px" controls-position="right" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="分类名称" name="typeName">
                <a-input v-model:value="form.typeName" style="width: 150px" controls-position="right" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="外径" name="outerDiameter" :rules="[{ required: true, message: '请输入外径' }]">
                <a-input-number v-model:value="form.outerDiameter" style="width: 150px" controls-position="right"
                  :min="0" addon-after="mm"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="重量" name="weight" :rules="[{ required: true, message: '请输入重量' }]">
                <a-input-number v-model:value="form.weight" style="width: 150px" controls-position="right" :min="0" addon-after="kg"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="有效长度" name="length" :rules="[{ required: true, message: '请输入有效长度' }]">
                <a-input-number v-model:value="form.length" style="width: 150px" controls-position="right" :min="0" addon-after="m"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="纵向抗压力" name="longitudinalPressure">
                <a-input-number v-model:value="form.longitudinalPressure" style="width: 150px" controls-position="right"
                  :min="0" addon-after="kN"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="纵向抗张力" name="longitudinalTension">
                <a-input-number v-model:value="form.longitudinalTension" style="width: 150px" controls-position="right"
                  :min="0" addon-after="kN"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="抗扭力" name="torsionResistance">
                <a-input-number v-model:value="form.torsionResistance" style="width: 150px" controls-position="right"
                  :min="0" addon-after="N·M"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="适合最大井眼" name="maxWell">
                <a-input-number v-model:value="form.maxWell" style="width: 150px" controls-position="right" :min="0" 
                addon-after="mm"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="适合最小井眼" name="minWell">
                <a-input-number v-model:value="form.minWell" style="width: 150px" controls-position="right" :min="0" 
                addon-after="mm"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="记录点" name="record">
                <a-input-number v-model:value="form.record" style="width: 150px" controls-position="right" :min="0" addon-after="m"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="耐温" name="temperatureResistance">
                <a-input v-model:value="form.temperatureResistance" style="width: 150px" controls-position="right" 
                addon-after="℃"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="运输长度" name="transportationLength">
                <a-input-number v-model:value="form.transportationLength" style="width: 150px" controls-position="right"
                  :min="0" addon-after="m"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="耐压" name="voltageResistance">
                <a-input-number v-model:value="form.voltageResistance" style="width: 150px" controls-position="right"
                  :min="0" addon-after="Mpa"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="抗拉伸力" name="minTensileResistance">
                <a-input-number v-model:value="form.minTensileResistance" style="width: 150px" controls-position="right"
                  :min="0" addon-after="lbf"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="抗压缩力" name="minCompressiveForces">
                <a-input-number v-model:value="form.minCompressiveForces" style="width: 150px" controls-position="right"
                  :min="0" addon-after="lbf"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="测井内容" name="loggingContent">
                <a-input v-model:value="form.loggingContent" style="width: 150px" controls-position="right" :min="0" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="制造厂商" name="manufacturer">
                <a-input v-model:value="form.manufacturer" style="width: 150px" controls-position="right" :min="0" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="文件id" name="fileId" hidden>
                <a-input v-model:value="form.fileId" style="width: 200px" controls-position="right" :min="0" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="上传仪器图片">
                <a-upload v-model:fileList="fileList" name="file" :before-upload="beforeUpload" :maxCount='1'
                  @remove="handleRemove">
                  <a-button style="width: 200px"><upload-outlined></upload-outlined>点击上传</a-button>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item>
                <a-button style="width: 200px; margin-left: 55px" @click="selectInsModalRef.openModal()">选择仪器图片</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </AntdConfirmModal>

      <!-- 仪器图片选择弹窗 -->
      <AntdConfirmModal :title="'选择仪器图片'" ref="selectInsModalRef" width="830px" :keepSlot="false" @confirm="submitInsPic">
        <div>
          <a-row>
            <a-col :span="3" v-for="(data, index) in imgList" :key="index">
              <a-card style="width: 80px; height: 135px; text-align: center; margin-top: 20px">
                <a-checkbox v-model:checked="instrumentImgChecked[data.id]" class="checkbox" @click="selectItem(data.id, index)" />
                <a-image :width="20" style="height: 100px;" :src="`/dev-api/ufs/preview/${data.fileId}`" />
              </a-card>
            </a-col>
          </a-row>
        </div>
        <br>
        <AntdZh>
          <a-pagination v-model:current="imgQuery.pageNum" v-model:pageSize="imgQuery.pageSize" :total="totalPic"
            @change="getImgList" />
        </AntdZh>
      </AntdConfirmModal>
    </div>
  </view>
</template>
<script setup>
import { ref } from "vue";
import { cloneDeep } from "lodash-es";
import { queryList, deleteOne, updateOne, createOne } from "@/api/tool/instrument";
import { queryList as imageList } from "@/api/images/images.js";
import { PlusOutlined, UploadOutlined } from "@ant-design/icons-vue";
import request from "@/utils/request";
import useApp from "@/hooks";
const { $, proxy } = useApp();
const modalRef = ref(null);
const selectInsModalRef = ref(null);
const total = ref(1);
const totalPic = ref(1);
const fileList = ref([]);
const fileForm = ref({
  file: null,
});
const instrumentType = ref('')
const imgQuery = ref({ imageType: "仪器", pageNum: 1, pageSize: 24, sortBy: "id", order: "DESC" });
const imgList = ref([]);
const instrumentImgChecked = ref([]);
const selectedInsPicId = ref('')
const title = ref(null);
const beforeUpload = (file) => {
  // 记录文件
  fileForm.value.file = file;
  // 直接停止上传
  return false;
};
function getImgList() {
  imageList(imgQuery.value).then((res) => {
    console.log('仪器图', res);
    imgList.value = res.content;
    totalPic.value = res.totalElements;
    console.log(imgList.value)
  });
}
function uploadFile() {
  const formData = new FormData();
  formData.append("file", fileForm.value.file);
  formData.append("bucketName", "test");
  request
    .post("/ufs/upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })
    .then((res) => {
      form.value.fileId = res.id;
      if (title.value == true) {
        createOne(form.value).then((res) => {
          modalRef.value.closeModal();
          getList();
        });
      } else if (title.value == false) {
        updateOne(form.value).then((res) => {
          modalRef.value.closeModal();
          getList();
        });
      }

      $.showToast({
        title: "上传成功",
        icon: "success",
      });
      getList();
      modalRef.value.closeModal();
    });
}

const data = reactive({
  form: {},
});
const { form } = toRefs(data);
const dataSource = ref([]);
// 定义表格列配置
const columns = [
  {
    title: "",
    dataIndex: "image",
    key: "image",
    fixed: "left",
    width: 60,
  },
  {
    title: "规格型号",
    dataIndex: "instrumentId",
    key: "instrumentId",
    width: 110,
  },
  {
    title: "仪器名称",
    dataIndex: "instrumentName",
    key: "instrumentName",
    width: 150,
  },
  {
    title: "装备类型",
    dataIndex: "instrumentType",
    key: "instrumentType",
    width: 90,
  },
  {
    title: "设备类别",
    dataIndex: "category",
    key: "category",
    width: 90,
  },
  {
    title: "主/子设备",
    dataIndex: "instrumentLevel",
    key: "instrumentLevel",
    width: 100,
  },
  {
    title: "装备系列",
    dataIndex: "instrumentSeries",
    key: "instrumentSeries",
    width: 90,
  },
  {
    title: "装备子系列",
    dataIndex: "instrumentChildSeries",
    key: "instrumentChildSeries",
    width: 110,
  },
  {
    title: "分类名称",
    dataIndex: "typeName",
    key: "typeName",
    width: 90,
  },
  {
    title: "外径(mm)",
    dataIndex: "outerDiameter",
    key: "outerDiameter",
    width: 90,
  },
  {
    title: "重量(kg)",
    dataIndex: "weight",
    key: "weight",
    width: 90,
  },
  {
    title: "有效长度(m)",
    dataIndex: "length",
    key: "length",
    width: 90,
  },
  {
    title: "纵向抗压力(kN)",
    dataIndex: "longitudinalPressure",
    key: "longitudinalPressure",
    width: 110,
  },
  {
    title: "纵向抗张力(kN)",
    dataIndex: "longitudinalTension",
    key: "longitudinalTension",
    width: 110,
  },
  {
    title: "抗扭力(N·M)",
    dataIndex: "torsionResistance",
    key: "torsionResistance",
    width: 90,
  },
  {
    title: "适合最大井眼(mm)",
    dataIndex: "maxWell",
    key: "maxWell",
    width: 120,
  },
  {
    title: "适合最小井眼(mm)",
    dataIndex: "minWell",
    key: "minWell",
    width: 120,
  },
  {
    title: "记录点(m)",
    dataIndex: "record",
    key: "record",
    width: 90,
  },
  {
    title: "耐温(℃)",
    dataIndex: "temperatureResistance",
    key: "temperatureResistance",
    width: 90,
  },
  {
    title: "运输长度(m)",
    dataIndex: "transportationLength",
    key: "transportationLength",
    width: 90,
  },
  {
    title: "耐压(MPa)",
    dataIndex: "voltageResistance",
    key: "voltageResistance",
    width: 90,
  },
  {
    title: "抗拉伸力(lbf)",
    dataIndex: "minTensileResistance",
    key: "minTensileResistance",
    width: 90,
  },
  {
    title: "抗压缩力(lbf)",
    dataIndex: "minCompressiveForces",
    key: "minCompressiveForces",
    width: 90,
  },
  {
    title: "测井内容",
    dataIndex: "loggingContent",
    key: "loggingContent",
    width: 90,
  },
  {
    title: "制造厂商",
    dataIndex: "manufacturer",
    key: "manufacturer",
    width: 90,
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    fixed: "right",
    width: 90,
  },
];
const searchKey = ref();
const query = ref({ pageNum: 1, pageSize: 10, sortBy: "id", searchKey: "" });
// const editableData = reactive({});
// const edit = (key) => {
//   editableData[key] = cloneDeep(dataSource.value.filter((item) => key === item.id)[0]);
// };
// 保存
// const save = (key) => {
//   updateOne(editableData[key]).then((res) => {
//     console.log("save", res);
//     $.showToast({
//       title: "修改成功",
//       icon: "success",
//     });
//     getList();
//     delete editableData[key];
//   });
// };

watch(() => instrumentType.value, (newVal) => {
  console.log('instrumentType.value', newVal)
  getList()
})

function deleteFile(key) {
  request
    .delete("/disk/dirs/0/files/" + form.value.fileId + "", {
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then((res) => {
      form.value.fileId = res.id;
      deleteOne(key).then((res) => {
        $.showToast({
          title: "删除成功",
          icon: "success",
        });
        getList();
        // delete editableData[key];
      });
      $.showToast({
        title: "删除仪器图片成功",
        icon: "success",
      });
      getList();
      modalRef.value.closeModal();
    });
}
// 删除
const del = (key) => {
  if (form.value.fileId != null) {
    deleteFile(key);
  } else {
    deleteOne(key).then((res) => {
      $.showToast({
        title: "删除成功",
        icon: "success",
      });
      getList();
      // delete editableData[key];
    });
  }
};
// const cancel = (key) => {
//   delete editableData[key];
// };

//编辑
function editItem(e) {
  form.value = e;
  title.value = false;
  getImgList();
  modalRef.value.openModal();
  resetFile()
}
// 新增
function addItem() {
  title.value = true;
  form.value = {};
  getImgList();
  modalRef.value.openModal();
}

// 仪器图片选择互斥
function selectItem(id, index) {
  // 处理选中状态
  // instrumentImgChecked.value = Object.fromEntries(
  //   Object.entries(instrumentImgChecked.value).map(([key, value]) => [key, key === id])
  // );
  Object.keys(instrumentImgChecked.value).forEach((key) => {
    instrumentImgChecked.value[key] = key === id;
  });
  // 获取选中的文件ID
  selectedInsPicId.value = imgList.value[index].fileId;
}

// 仪器图片提交
function submitInsPic() {
  form.value.fileId = selectedInsPicId.value
  selectInsModalRef.value.closeModal();
}
// 移除文件
const handleRemove = file => {
  fileForm.value.file = null
};
// 文件置空
function resetFile() {
  form.value.fileId = null;
  selectedInsPicId.value = null
  instrumentImgChecked.value = []
}
/** 提交按钮 */
function submitForm() {
  if (fileForm.value.file != null) {
    uploadFile();
    return;
  } else if (title.value == true) {
    createOne(form.value).then((res) => {
      // form.value.fileId = null;
      modalRef.value.closeModal();
      getList();
    });
  } else if (title.value == false) {
    updateOne(form.value).then((res) => {
      // form.value.fileId = null;
      modalRef.value.closeModal();
      getList();
    });
  }
  resetFile()
}

/** 查询列表 */
function getList() {
  if (instrumentType.value == 'CPLog') {
    query.value.searchKey = 'CPLog'
    queryList(query.value).then((response) => {
      dataSource.value = response.content;
      total.value = response.totalElements;
    });
  } else if (instrumentType.value == '5700') {
    query.value.searchKey = '5700'
    queryList(query.value).then((response) => {
      dataSource.value = response.content;
      total.value = response.totalElements;
    });
  } else {
    queryList(query.value).then((response) => {
      dataSource.value = response.content;
      total.value = response.totalElements;
    });
  }
}
getList();

/** 搜索按钮操作 */
function handleQuery() {
  query.value.searchKey = searchKey;
  getList();
}

/** 表单重置 */
function reset() {
  searchKey.value = "";
  instrumentType.value = ''
  query.value = {
    pageNum: 1,
    pageSize: 10,
    sortBy: "id",
    searchKey: "",
  };
  getList();
}

</script>
<style>
.checkbox {
  position: absolute;
  top: 0;
  left: 0;
}
</style>
